[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  23. import type { CrowiRequest } from '~/interfaces/crowi-request';
  24. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  25. // import { useRendererSettings } from '~/stores/renderer';
  26. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  27. import type { EditorConfig } from '~/interfaces/editor-settings';
  28. import type { CustomWindow } from '~/interfaces/global';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  36. import { useRedirectFrom } from '~/stores/page-redirect';
  37. import {
  38. EditorMode,
  39. useEditorMode, useSelectedGrant,
  40. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  41. } from '~/stores/ui';
  42. import loggerFactory from '~/utils/logger';
  43. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  44. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  45. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  46. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  49. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  50. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  51. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  52. import {
  53. useCurrentUser,
  54. useIsLatestRevision, useCurrentRevisionId,
  55. useIsForbidden, useIsNotFound, useIsSharedUser,
  56. useIsEnabledStaleNotification, useIsIdenticalPath,
  57. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  58. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  59. useIsAclEnabled, useIsSearchPage,
  60. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  61. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  62. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  63. } from '../stores/context';
  64. import {
  65. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  66. } from './utils/commons';
  67. // import { useCurrentPageSWR } from '../stores/page';
  68. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  69. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  70. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  71. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  72. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  73. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  74. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  75. const logger = loggerFactory('growi:pages:all');
  76. const {
  77. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  78. } = pagePathUtils;
  79. const { removeHeadingSlash } = pathUtils;
  80. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  81. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  82. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  83. {
  84. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  85. return v?.data != null
  86. && v?.data.toObject != null
  87. && v?.meta != null
  88. && isIPageInfoForEntity(v.meta);
  89. },
  90. serialize: (v) => {
  91. return {
  92. data: superjson.stringify(v.data.toObject()),
  93. meta: superjson.stringify(v.meta),
  94. };
  95. },
  96. deserialize: (v) => {
  97. return {
  98. data: superjson.parse(v.data),
  99. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  100. };
  101. },
  102. },
  103. 'IPageToShowRevisionWithMetaTransformer',
  104. );
  105. const IdenticalPathPage = (): JSX.Element => {
  106. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  107. return <IdenticalPathPage />;
  108. };
  109. const PutbackPageModal = (): JSX.Element => {
  110. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  111. return <PutbackPageModal />;
  112. };
  113. type Props = CommonProps & {
  114. currentUser: IUser,
  115. pageWithMeta: IPageToShowRevisionWithMeta | null,
  116. // pageUser?: any,
  117. redirectFrom?: string;
  118. // shareLinkId?: string;
  119. isLatestRevision?: boolean,
  120. currentRevisionId?: string,
  121. isIdenticalPathPage?: boolean,
  122. isForbidden: boolean,
  123. isNotFound: boolean,
  124. isNotCreatablePage: boolean,
  125. // isAbleToDeleteCompletely: boolean,
  126. isSearchServiceConfigured: boolean,
  127. isSearchServiceReachable: boolean,
  128. isSearchScopeChildrenAsDefault: boolean,
  129. isSlackConfigured: boolean,
  130. // isMailerSetup: boolean,
  131. isAclEnabled: boolean,
  132. // hasSlackConfig: boolean,
  133. drawioUri: string,
  134. hackmdUri: string,
  135. noCdn: string,
  136. // highlightJsStyle: string,
  137. isAllReplyShown: boolean,
  138. isContainerFluid: boolean,
  139. editorConfig: EditorConfig,
  140. isEnabledStaleNotification: boolean,
  141. // isEnabledLinebreaks: boolean,
  142. // isEnabledLinebreaksInComments: boolean,
  143. adminPreferredIndentSize: number,
  144. isIndentSizeForced: boolean,
  145. disableLinkSharing: boolean,
  146. rendererConfig: RendererConfig,
  147. // UI
  148. userUISettings?: IUserUISettings
  149. // Sidebar
  150. sidebarConfig: ISidebarConfig,
  151. };
  152. const GrowiPage: NextPage<Props> = (props: Props) => {
  153. // const { t } = useTranslation();
  154. const router = useRouter();
  155. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  156. // register global EventEmitter
  157. if (isClient()) {
  158. (window as CustomWindow).globalEmitter = new EventEmitter();
  159. }
  160. // commons
  161. useEditorConfig(props.editorConfig);
  162. useCsrfToken(props.csrfToken);
  163. useCustomizedLogoSrc(props.customizedLogoSrc);
  164. // UserUISettings
  165. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  166. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  167. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  168. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  169. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  170. // page
  171. useIsLatestRevision(props.isLatestRevision);
  172. useIsContainerFluid(props.isContainerFluid);
  173. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  174. useIsForbidden(props.isForbidden);
  175. useIsNotFound(props.isNotFound);
  176. // useIsNotCreatable(props.IsNotCreatable);
  177. useRedirectFrom(props.redirectFrom);
  178. // useShared();
  179. // useShareLinkId(props.shareLinkId);
  180. useIsSharedUser(false); // this page cann't be routed for '/share'
  181. useIsIdenticalPath(false); // TODO: need to initialize from props
  182. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  183. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  184. useIsSearchPage(false);
  185. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  186. useIsSearchServiceReachable(props.isSearchServiceReachable);
  187. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  188. useIsSlackConfigured(props.isSlackConfigured);
  189. // useIsMailerSetup(props.isMailerSetup);
  190. useIsAclEnabled(props.isAclEnabled);
  191. // useHasSlackConfig(props.hasSlackConfig);
  192. useDrawioUri(props.drawioUri);
  193. useHackmdUri(props.hackmdUri);
  194. // useNoCdn(props.noCdn);
  195. useDefaultIndentSize(props.adminPreferredIndentSize);
  196. useIsIndentSizeForced(props.isIndentSizeForced);
  197. useDisableLinkSharing(props.disableLinkSharing);
  198. useRendererConfig(props.rendererConfig);
  199. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  200. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  201. useIsAllReplyShown(props.isAllReplyShown);
  202. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  203. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  204. const { pageWithMeta, userUISettings } = props;
  205. const pageId = pageWithMeta?.data._id;
  206. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  207. useCurrentPageId(pageId ?? null);
  208. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  209. useCurrentPathname(props.currentPathname);
  210. useCurrentRevisionId(props.currentRevisionId);
  211. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  212. useEditingMarkdown(pageWithMeta?.data.revision?.body ?? '');
  213. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  214. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  215. const { getClassNamesByEditorMode } = useEditorMode();
  216. const shouldRenderPutbackPageModal = pageWithMeta != null
  217. ? _isTrashPage(pageWithMeta.data.path)
  218. : false;
  219. // sync grant data
  220. useEffect(() => {
  221. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  222. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  223. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  224. useEffect(() => {
  225. const decodedURI = decodeURI(window.location.pathname);
  226. if (isClient() && decodedURI !== props.currentPathname) {
  227. router.replace(props.currentPathname, undefined, { shallow: true });
  228. }
  229. }, [props.currentPathname, router]);
  230. const classNames: string[] = [];
  231. const isSidebar = pagePath === '/Sidebar';
  232. classNames.push(...getClassNamesByEditorMode(isSidebar));
  233. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  234. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  235. ? null
  236. : currentPage.expandContentWidth;
  237. const isContainerFluidDefault = props.isContainerFluid;
  238. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  239. return (
  240. <>
  241. <Head>
  242. {/*
  243. {renderScriptTagByName('drawio-viewer')}
  244. {renderScriptTagByName('highlight-addons')}
  245. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  246. */}
  247. </Head>
  248. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={isContainerFluid}>
  249. <div className="h-100 d-flex flex-column justify-content-between">
  250. <header className="py-0 position-relative">
  251. <div id="grw-subnav-container">
  252. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  253. </div>
  254. </header>
  255. <div className="d-edit-none">
  256. <GrowiSubNavigationSwitcher />
  257. </div>
  258. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  259. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  260. <div className="flex-grow-1">
  261. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  262. <div id="content-main" className="content-main grw-container-convertible">
  263. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  264. { !props.isIdenticalPathPage && (
  265. <>
  266. <PageAlerts />
  267. { props.isForbidden && <ForbiddenPage /> }
  268. { props.isNotCreatablePage && <NotCreatablePage />}
  269. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  270. {/* <DisplaySwitcher /> */}
  271. {/* <PageStatusAlert /> */}
  272. </>
  273. ) }
  274. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  275. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  276. <div id="revision-toc-content" className="revision-toc-content"></div>
  277. </div>
  278. </div> */}
  279. </div>
  280. </div>
  281. </div>
  282. { !props.isIdenticalPathPage && !props.isNotFound && (
  283. <footer className="footer d-edit-none">
  284. { pageWithMeta != null && !isTopPagePath && (<Comments pageId={pageId} revision={pageWithMeta.data.revision} />) }
  285. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  286. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  287. ) }
  288. <CurrentPageContentFooter />
  289. </footer>
  290. )}
  291. <UnsavedAlertDialog />
  292. <DescendantsPageListModal />
  293. <HandsontableModal />
  294. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  295. </div>
  296. </BasicLayout>
  297. </>
  298. );
  299. };
  300. function getPageIdFromPathname(currentPathname: string): string | null {
  301. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  302. }
  303. class MultiplePagesHitsError extends ExtensibleCustomError {
  304. pagePath: string;
  305. constructor(pagePath: string) {
  306. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  307. this.pagePath = pagePath;
  308. }
  309. }
  310. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  311. const { model: mongooseModel } = await import('mongoose');
  312. const req: CrowiRequest = context.req as CrowiRequest;
  313. const { crowi } = req;
  314. const { revisionId } = req.query;
  315. const Page = crowi.model('Page') as PageModel;
  316. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  317. const { pageService } = crowi;
  318. let currentPathname = props.currentPathname;
  319. const pageId = getPageIdFromPathname(currentPathname);
  320. const isPermalink = _isPermalink(currentPathname);
  321. const { user } = req;
  322. if (!isPermalink) {
  323. // check redirects
  324. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  325. if (chains != null) {
  326. // overwrite currentPathname
  327. currentPathname = chains.end.toPath;
  328. props.currentPathname = currentPathname;
  329. // set redirectFrom
  330. props.redirectFrom = chains.start.fromPath;
  331. }
  332. // check whether the specified page path hits to multiple pages
  333. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  334. if (count > 1) {
  335. throw new MultiplePagesHitsError(currentPathname);
  336. }
  337. }
  338. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  339. const page = pageWithMeta?.data as unknown as PageDocument;
  340. // add user to seen users
  341. if (page != null && user != null) {
  342. await page.seen(user);
  343. }
  344. // populate & check if the revision is latest
  345. if (page != null) {
  346. page.initLatestRevisionField(revisionId);
  347. await page.populateDataToShowRevision();
  348. props.isLatestRevision = page.isLatestRevision();
  349. }
  350. if (typeof revisionId === 'string' || typeof revisionId === 'undefined') {
  351. props.currentRevisionId = props.isLatestRevision && page.latestRevision != null ? page.latestRevision.toString() : revisionId;
  352. }
  353. props.pageWithMeta = pageWithMeta;
  354. }
  355. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  356. const { model: mongooseModel } = await import('mongoose');
  357. const req = context.req as CrowiRequest<IUserHasId & any>;
  358. const { user } = req;
  359. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  360. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  361. if (userUISettings != null) {
  362. props.userUISettings = userUISettings.toObject();
  363. }
  364. }
  365. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  366. const req: CrowiRequest = context.req as CrowiRequest;
  367. const { crowi } = req;
  368. const Page = crowi.model('Page') as PageModel;
  369. const { currentPathname } = props;
  370. const pageId = getPageIdFromPathname(currentPathname);
  371. const isPermalink = _isPermalink(currentPathname);
  372. const page = props.pageWithMeta?.data;
  373. if (props.isIdenticalPathPage) {
  374. // TBD
  375. }
  376. else if (page == null) {
  377. props.isNotFound = true;
  378. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  379. // check the page is forbidden or just does not exist.
  380. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  381. props.isForbidden = count > 0;
  382. }
  383. else {
  384. props.isNotFound = page.isEmpty;
  385. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  386. if (isPermalink && page.isEmpty) {
  387. props.currentPathname = page.path;
  388. }
  389. // /path/to/page ==> /62a88db47fed8b2d94f30000
  390. if (!isPermalink && !page.isEmpty) {
  391. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  392. if (!isToppage) {
  393. props.currentPathname = `/${page._id}`;
  394. }
  395. }
  396. }
  397. }
  398. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  399. // const req: CrowiRequest = context.req as CrowiRequest;
  400. // const { crowi } = req;
  401. // const UserModel = crowi.model('User');
  402. // if (isUserPage(props.currentPagePath)) {
  403. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  404. // if (user != null) {
  405. // props.pageUser = JSON.stringify(user.toObject());
  406. // }
  407. // }
  408. // }
  409. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  410. const req: CrowiRequest = context.req as CrowiRequest;
  411. const { crowi } = req;
  412. const {
  413. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  414. } = crowi;
  415. props.isSearchServiceConfigured = searchService.isConfigured;
  416. props.isSearchServiceReachable = searchService.isReachable;
  417. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  418. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  419. // props.isMailerSetup = mailService.isMailerSetup;
  420. props.isAclEnabled = aclService.isAclEnabled();
  421. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  422. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  423. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  424. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  425. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  426. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  427. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  428. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  429. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  430. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  431. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  432. props.editorConfig = {
  433. upload: {
  434. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  435. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  436. },
  437. };
  438. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  439. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  440. props.rendererConfig = {
  441. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  442. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  443. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  444. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  445. plantumlUri: process.env.PLANTUML_URI ?? null,
  446. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  447. // XSS Options
  448. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  449. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  450. tagWhiteList: crowi.xssService.getTagWhiteList(),
  451. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  452. };
  453. props.sidebarConfig = {
  454. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  455. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  456. };
  457. }
  458. /**
  459. * for Server Side Translations
  460. * @param context
  461. * @param props
  462. * @param namespacesRequired
  463. */
  464. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  465. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  466. props._nextI18Next = nextI18NextConfig._nextI18Next;
  467. }
  468. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  469. const req = context.req as CrowiRequest<IUserHasId & any>;
  470. const { user } = req;
  471. const result = await getServerSideCommonProps(context);
  472. // check for presence
  473. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  474. if (!('props' in result)) {
  475. throw new Error('invalid getSSP result');
  476. }
  477. const props: Props = result.props as Props;
  478. if (props.redirectDestination != null) {
  479. return {
  480. redirect: {
  481. permanent: false,
  482. destination: props.redirectDestination,
  483. },
  484. };
  485. }
  486. if (user != null) {
  487. props.currentUser = user.toObject();
  488. }
  489. try {
  490. await injectPageData(context, props);
  491. }
  492. catch (err) {
  493. if (err instanceof MultiplePagesHitsError) {
  494. props.isIdenticalPathPage = true;
  495. }
  496. else {
  497. throw err;
  498. }
  499. }
  500. await injectUserUISettings(context, props);
  501. await injectRoutingInformation(context, props);
  502. injectServerConfigurations(context, props);
  503. await injectNextI18NextConfigurations(context, props, ['translation']);
  504. return {
  505. props,
  506. };
  507. };
  508. export default GrowiPage;